package com.qianfeng.realms;

import com.qianfeng.entity.User;
import com.qianfeng.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import sun.applet.Main;


public class ShoriRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //获取用户信息
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        if (token.getUsername().isEmpty()){
            throw new UnknownAccountException();
        }
        if(token.getPassword()==null || token.getPassword().length==0){
            throw new IncorrectCredentialsException();
        }
        //通过前端传送过来的用户名查询数据库数据是否存在
        User user = userService.getUserByUserName(token.getUsername());
        if (user==null){
            throw new UnknownAccountException();
        }
        ByteSource salt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUserLoginName(),user.getUserPassword(),salt,getName());
        return info;
    }


    public static void main (String[] args){
        String username="lilei";
        String password="lilei";//ca3b6802a9e41eb92f7c8bd9c44df8d3
        String salt="lilei";
        Md5Hash hash = new Md5Hash(password,salt,1024);
        System.out.println(hash.toString());

    }
}
